import { reactive, onMounted, defineComponent, toRefs, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dictApi from '@/api/system/dict-api'
import ZlrtTable from '@/components/zlrt-table/table.vue'
import ZlrtSearch from '@/components/zlrt-search/search.vue'
import TableContext from '@/components/zlrt-table/table-context'

export default defineComponent({
  components: {
    ZlrtTable,
    ZlrtSearch
  },
  setup () {
    const disabledOptions = [
      { label: '正常', value: true },
      { label: '停用', value: false }
    ]

    const ctx = reactive(new TableContext(getCurrentInstance(), {
      title: '字典类型',
      api: dictApi,
      columns: [
        { prop: 'dictName', label: '字典名称', valueType: 'input' },
        { prop: 'dictType', label: '字典类型', valueType: 'input', slot: true },
        { prop: 'disabled', label: '状态', slot: true, valueType: 'select', options: disabledOptions },
        { prop: 'operation', label: '操作', slot: true }
      ],
      rules: {
        dictName: [{ required: true, message: '请输入字典名称', trigger: 'blur' }],
        dictType: [{ required: true, message: '请输入字典类型', trigger: 'blur' }],
        disabled: [{ required: true, message: '请选择状态', trigger: 'change' }]
      },
      other: {
        statusChanged: (row) => {
          const { dictName, disabled } = row
          ElMessageBox.confirm(`确认要${disabled ? '停用' : '启用'}"${dictName}"字典数据吗？`, '温馨提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            draggable: true
          })
            .then(async () => {
              const res = await dictApi.save(row)
              if (res.code === 200) {
                ElMessage.success(`${disabled ? '停用' : '启用'}成功`)
              } else {
                row.disabled = !disabled
              }
            })
            .catch(() => {
              row.disabled = !disabled
            })
        }
      }
    }))

    const data = reactive({
      ctx,
      disabledOptions
    })

    // init
    onMounted(() => {
      ctx.loadData()
    })

    return {
      ...toRefs(data)
    }
  }
})
